package com.digitalchina.lxnsy.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.SetPayPasswordOneActivity;
import com.digitalchina.lxnsy.activity.old.WithdrawHistoryListActivity;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.CashLimitNewVO;
import com.digitalchina.lxnsy.entity.UserInfo3rdPatyVO;
import com.digitalchina.lxnsy.toolkit.EncryptUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.model.HttpParams;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/10/8 17:49
 * 修改备注：
 * ================================================
 */
public class WithdrawBankFragment extends BaseV4Fragment {

    @Bind(R.id.tv_bank)
    TextView tvBank;
    @Bind(R.id.tv_change)
    TextView tvChange;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.tv_all)
    TextView tvAll;
    @Bind(R.id.tv_avail_price)
    TextView tvAvailPrice;
    @Bind(R.id.tv_freeze_price)
    TextView tvFreezePrice;
    @Bind(R.id.bt_submit)
    Button btSubmit;
    @Bind(R.id.tv_info)
    TextView tvInfo;

    private PasswordKeypad mKeypad;
//    private List<BankListVO> voList = new ArrayList<>();

    CashLimitNewVO cashLimitNewVO;

    private String bankId = "";
    private String allPrice = "";
    private String mActualBal = "";
    private String mCanUseBal = "";
    private String mFreezeMoney = "";

    //绑定微信
    private static final int WX_AUTH = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private String openId = "";
    private String unionid = "";
    private String nickname = "";

    private String bindType = "";
    private String paymentPwd = "";

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_withdraw_bank);
    }

    public void cashLimitNew(CashLimitNewVO vo) {
        cashLimitNewVO = vo;

        String s1 = String.format(tvAvailPrice.getText().toString(), mCanUseBal);
        tvAvailPrice.setText(s1);

        String s2 = String.format(tvFreezePrice.getText().toString(), vo.getMin(), vo.getMax());
        tvFreezePrice.setText(s2);

        String s3 = String.format(tvInfo.getText().toString(), vo.getTimes(), vo.getFreeAmount(), String.valueOf(Double.parseDouble(vo.getWxScale())*100));
        tvInfo.setText(s3);
    }

    public  void set3rdUserInfo(UserInfo3rdPatyVO vo){
        LogUtils.e(vo);
        tvBank.setText(vo.getNickName());
        openId = vo.getOpenId();
        unionid = vo.getAccountId();
        nickname = vo.getNickName();
    }

    @Override
    public void initMember() {

        mActualBal = getArguments().getString("ActualBal");
        mCanUseBal = getArguments().getString("CanUseBal");
        mFreezeMoney = getArguments().getString("FreezeMoney");

        allPrice = mActualBal;
//        tvAvailPrice.setText("可用金额￥" + mActualBal);
//        tvFreezePrice.setText("暂不可提现金额￥" + mFreezeMoney);

        // 银行卡列表
//        BusinessWallet.bankCardList(getActivity(), mHandler);

        // 余额
        // BusinessWallet.getBalance(getActivity(), mHandler);

        mKeypad = new PasswordKeypad();
        mKeypad.setPasswordCount(6);

    }

    @Override
    public void addListener() {
        mKeypad.setCallback(new Callback() {
            @Override
            public void onForgetPassword() {
                GotoUtil.gotoActivity(getActivity(), SetPayPasswordOneActivity.class, true, "type", 1);
            }

            @Override
            public void onInputCompleted(CharSequence password) {
                paymentPwd = password.toString();
                cashLimitNew();
                //BusinessWallet.withdrawCashForBank(getActivity(), psw, etMoney.getText().toString(), bankId, mHandler);
            }

            @Override
            public void onPasswordCorrectly() {
                mKeypad.dismiss();
            }

            @Override
            public void onCancel() {
                //todo:做一些埋点类的需求
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);


                switch (msg.what) {
                    case MSG.MSG_BANK_CARD_LIST_SUCCESS: // 银行卡列表
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_BANK_CARD_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_WITHDRAW_CASH_SUCCESS: // 提现
                        showToast("提现申请成功");
                        mKeypad.setPasswordState(true);
                        break;
                    case MSG.MSG_WITHDRAW_CASH_FIELD:
                        showToast(msg.obj.toString());
                        mKeypad.setPasswordState(false, msg.obj.toString());
                        break;
                    case MSG.MSG_GET_BALANCE_SUCCESS: // 余额
//                        MyWalletVO myWalletVO = FastJsonUtil.getBean(msg.obj.toString(), "", MyWalletVO.class);
//
//                        /**
//                         * actualBal    余额
//                         * freezeMoney 总共冻结保障金(忽略）
//                         * canUseBal  可用余额
//                         */
//
//
//
//                        if (myWalletVO != null) {
//                            allPrice = myWalletVO.getActualBal();
//                            tvAvailPrice.setText("可用金额￥" + myWalletVO.getActualBal());
//                            tvFreezePrice.setText("暂不可提现金额￥" + myWalletVO.getFreezeMoney());
//                        }
                        break;
                    case MSG.MSG_GET_BALANCE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case WX_AUTH: // 微信授权
                        BusinessAccount.bind3rdUserInfo(getActivity(), openId, unionid, "WX", nickname, mHandler);
                        break;

                    case MSG_S_0:
                        mKeypad.dismiss();
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .content("提现申请成功")
                                .positiveText("确定")
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        getActivity().finish();
                                        GotoUtil.gotoActivity(getActivity(), WithdrawHistoryListActivity.class);
                                    }
                                })
                                .show();
                        break;
                    case MSG_F_0:
                        mKeypad.setPasswordState(false, msg.obj.toString());
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
//        voList = FastJsonUtil.getListBean(object.toString(), BankListVO.class);
//
//
//        if (voList != null && voList.size() > 0) {
//            BankListVO vo = voList.get(0);
//            bankId = vo.getId();
//            tvBank.setText(vo.getBankName() + "（" + vo.getCardNumber() + "）");
//        } else {
//            tvBank.setText("暂无银行卡");
//            tvChange.setText("新增银行卡");
//        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_change, R.id.bt_submit, R.id.tv_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_change:
//                Intent intent = new Intent(getActivity(), BankListActivity.class);
//                startActivityForResult(intent, 99);
                break;
            case R.id.bt_submit:
                showPassword();
                break;
            case R.id.tv_all: // 全部提现
                if (StringUtil.isStrEmpty(allPrice)) {
                    showToast("余额获取失败，请重试。");
                } else {
                    etMoney.setText(allPrice);
                }
                break;
        }
    }

    private void showPassword() {

        if (StringUtil.isStrEmpty(openId)) {
            showToast("请绑定微信账号");
            return;
        }

        if (StringUtil.isStrEmpty(etMoney.getText().toString())) {
            showToast("请输入提取金额");
            return;
        }
        mKeypad.show(getActivity().getSupportFragmentManager(), "PasswordKeypad");
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Activity.RESULT_OK) {
//            BankListVO vo = (BankListVO) data.getSerializableExtra("BankListVO");
//            if (vo != null) {
//                bankId = vo.getId();
//                tvBank.setText(vo.getBankName() + "（" + vo.getCardNumber() + "）");
//                tvChange.setText("更换银行卡");
//            }
//        }
//    }



    //提现
    public void cashLimitNew() {
        HttpParams params = new HttpParams();

        params.put("userAccId", UserXML.getUserId(getActivity()));
        params.put("paymentPwd", EncryptUtil.SHA1(paymentPwd));
        params.put("withdrawWay", "2");//提现方式 银行卡 0 支付宝 1 微信 2
        params.put("payAmt", etMoney.getText().toString());
        params.put("openid", openId);
        params.put("wxNickName", nickname);


        OkHttpUtil.post(getActivity(), URL.URL_WITHDRAW_CASH_NEW, "请稍候...", params, mHandler,
                MSG_S_0, MSG_F_0);
    }


}
